﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Models;
using System.Threading;

namespace ChinaDynastyTours.Views
{
    public partial class PaymentConfirmForm :DevExpress.XtraEditors.XtraForm
    {
        //输入参数
        //public string _TourGroupID { get; set; }//团ID
        //public string _TourGroupState { get; set; }//团状态
        
        private DataTable _dtPaymentConfirm;
        private DataTable _dtPayDetail;

        public PaymentConfirmForm()
        {
            InitializeComponent();

            tbPayTime.DateTime = DateTime.Now;
        }
        private void ButtonStatus()
        {
            if (payApplyGridView.FocusedRowHandle < 0)
            {
                btnCancelPayRequest.Enabled = false;
                btnConfirmPayment.Enabled = false;
                return;
            }

            bool bPayStatus = payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "PayStatus").ToString() == PayStatusEnum.未付.ToString();
            btnCancelPayRequest.Enabled = bPayStatus;
            btnConfirmPayment.Enabled = bPayStatus;
        }

        private void btnProviders_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ProviderSelectedToolForm providerServiceForm = new ProviderSelectedToolForm()
            {
                _ProviderTypes = new ProviderTypeEnum[] {
                ProviderTypeEnum.宾馆,ProviderTypeEnum.餐厅,ProviderTypeEnum.旅行社,ProviderTypeEnum.汽车,ProviderTypeEnum.演出,
                ProviderTypeEnum.景点,ProviderTypeEnum.火车票,ProviderTypeEnum.飞机票 
            }
            };

            if (providerServiceForm.ShowDialog(this) == DialogResult.OK)
            {
                DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                btnEdit.Tag = providerServiceForm.ReturnProviderID;
                btnEdit.EditValue = providerServiceForm.ReturnProviderName;
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            string providerId = btnProviders.Tag == null ? "" : btnProviders.Tag.ToString();

            _dtPaymentConfirm = PayApplyCtrl.GetPayApplyDataByProviderID(providerId);
            payApplyGridControl.DataSource = _dtPaymentConfirm;

            if (payApplyGridView.FocusedRowHandle < 0)
            {
                payDetailGridControl.DataSource = null;
            }
            else
            {
                string payApplyId = payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "PayApplyID").ToString();
                _dtPayDetail = PayDetailCtrl.GetPayDetailDataByPayApplyId(payApplyId);
                payDetailGridControl.DataSource = _dtPayDetail;
            }
            ButtonStatus();

        }

        private void payApplyGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            ButtonStatus();

            if (e.FocusedRowHandle < 0) return;

            string payApplyId = payApplyGridView.GetRowCellValue(e.FocusedRowHandle, "PayApplyID").ToString();
            _dtPayDetail = PayDetailCtrl.GetPayDetailDataByPayApplyId(payApplyId);
            payDetailGridControl.DataSource = _dtPayDetail;
            //_dtPayDetail.ColumnChanged += new DataColumnChangeEventHandler(PayDetail_ColumnChanged);
        }
        private void btnModifyVoucher_Click(object sender, EventArgs e)
        {
            if (payApplyGridView.FocusedRowHandle < 0) return;

            if (payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "Voucher").ToString() != "")
            {
                MessageBox.Show("已有凭证号不能修改");
                return;
            }

            VoucherModifyForm voucherForm = new VoucherModifyForm();
            if (voucherForm.ShowDialog(this) == DialogResult.OK)
            {
                string payApplyId = payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "PayApplyID").ToString();
                PayApplyCtrl.UpdatePayApplyVoucher(voucherForm.tbVoucher.Text, payApplyId);
                //刷新界面
                payApplyGridView.SetRowCellValue(payApplyGridView.FocusedRowHandle, "Voucher", voucherForm.tbVoucher.Text);
            }
        }

        private void btnModifyRemark_Click(object sender, EventArgs e)
        {
            if (payDetailGridView.FocusedRowHandle < 0) return;

            RemarkModifyForm remarkForm = new RemarkModifyForm();

            if (remarkForm.ShowDialog(this) == DialogResult.OK)
            {
                string payDetailId = payDetailGridView.GetRowCellValue(payDetailGridView.FocusedRowHandle, "PayDetailID").ToString();
                string remark = payDetailGridView.GetRowCellValue(payDetailGridView.FocusedRowHandle, "Remark").ToString() + " " + remarkForm.tbRemark.Text;
                PayDetailCtrl.UpdatePayDetailRemark(remark, payDetailId);
                //刷新界面
                payDetailGridView.SetRowCellValue(payDetailGridView.FocusedRowHandle, "Remark", remark);
            }

        }
        //void PayDetail_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        //{
        //    string payApplyID = e.Row["PayApplyID"].ToString();
        //    //string realPayment = RealPayment.SummaryItem.SummaryValue.ToString();

        //    decimal rmbAmount = 0;
        //    foreach (DataRow dr in _dtPayDetail.Rows)
        //    {
        //        rmbAmount += decimal.Parse(dr["RealPayment"].ToString());
        //    }

        //    //更新詳情中的實際付款額
        //    PayApplyCtrl.UpdateRealPaymentForPayApply(payApplyID, rmbAmount);
        //    PayDetailCtrl.UpdateRealPaymentForPayDetail(e.Row["PayDetailID"].ToString(), rmbAmount);

        //    //更新付款申请单项“RealPayment实际付款额”,引发数据更新
        //    DataRowView drv = BindingContext[_dtPaymentConfirm].Current as DataRowView;
        //    drv["RealPayment"] = rmbAmount;
        //}
        
        /// <summary>
        /// 财务用新增付款
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNewAddPayment_Click(object sender, EventArgs e)
        {
            AddPaymentForm addform = new AddPaymentForm();
            if (addform.ShowDialog(this) == DialogResult.OK)
            {
                btnRefresh.PerformClick();//刷新
            }
        }
        
        /// <summary>
        /// 财务付款确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfirmPayment_Click(object sender, EventArgs e)
        {
            PaymentMethodForm payForm = new PaymentMethodForm();
            payForm.tbRemark.EditValue = payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "Remark");

            if (payForm.ShowDialog(this) == DialogResult.OK)//获取付款形式及凭证号
            {
                string payApplyId = payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "PayApplyID").ToString();

                if (payApplyId != "" && (_dtPayDetail != null && _dtPayDetail.Rows.Count > 0))
                {
                    //修改付款申请单状态‘财务付款状态’为‘已付’（现金、汇款、支票）或修改状态为‘预付’
                    PayStatusEnum Status = PayStatusEnum.未付;
                    decimal applyPay = 0;
                    Dictionary<int, decimal> applyPaysAndExpenseIds = new Dictionary<int, decimal>();
                    //Dictionary<int, string> tourGroupIds = new Dictionary<int, string>();
                    string currentUser = UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name);//当前登录者

                    switch (payForm.bigClassGroup.SelectedIndex)
                    {
                        case 0://支付
                            Status = PayStatusEnum.已付;
                            //switch (payForm.payGroup.SelectedIndex)
                            //这个判断有点怪，为什么不把SelectedIndex直接放到Items[SelectedIndex]里面？    
                            //{
                            //    case 0:
                            //        PayApplyCtrl.UpdatePayApplyPayStatus(tbPayTime.DateTime, Status, payForm.payGroup.Properties.Items[0].Description, payForm.tbVoucher.Text, payForm.tbRemark.Text, currentUser, payApplyId);
                            //        break;
                            //    case 1:
                            //        PayApplyCtrl.UpdatePayApplyPayStatus(tbPayTime.DateTime, Status, payForm.payGroup.Properties.Items[1].Description, payForm.tbVoucher.Text, payForm.tbRemark.Text, currentUser, payApplyId);
                            //        break;
                            //    case 2:
                            //        PayApplyCtrl.UpdatePayApplyPayStatus(tbPayTime.DateTime, Status, payForm.payGroup.Properties.Items[2].Description, payForm.tbVoucher.Text, payForm.tbRemark.Text, currentUser, payApplyId);
                            //        break;
                            //    default:
                            //        break;
                            //       
                            //}

                            PayApplyCtrl.UpdatePayApplyPayStatus(tbPayTime.DateTime, Status, payForm.payGroup.Properties.Items[payForm.payGroup.SelectedIndex].Description, payForm.tbVoucher.Text, payForm.tbRemark.Text, currentUser, payApplyId);

                            //生成付款单表
                            PayEntity payEntity = new PayEntity();
                            payEntity.ProviderID = int.Parse(payApplyGridView.GetFocusedRowCellValue("ProviderID").ToString());
                            payEntity.ProviderName = payApplyGridView.GetFocusedRowCellValue("ProviderName").ToString();
                            payEntity.PayAmount = decimal.Parse(payApplyGridView.GetFocusedRowCellValue("TotalpaymentL").ToString());
                            payEntity.Applicants = currentUser;
                            payEntity.PayTime = tbPayTime.DateTime.ToString("yyyy-MM-dd");
                            payEntity.ReducedItem = "";
                            payEntity.ReduceAmount = 0;
                            payEntity.PaymentMethod = payForm.payGroup.Properties.Items[payForm.payGroup.SelectedIndex].Description;
                            payEntity.Voucher = payForm.tbVoucher.Text;
                            payEntity.Remark = payForm.tbRemark.Text;
                            string payID = PayApplyCtrl.CreatePayData(payEntity);

                            //更新付款详情表
                            PayApplyCtrl.UpdatePayDetailbyPayApplyId(payID, payApplyId);


                            //修改费用表‘支付状态’为‘已付’,并将本次申请额送到后台，由Sql完成‘已支付总额’计算后更新‘已支付总额’
                            for (int i = 0; i < _dtPayDetail.Rows.Count; i++)
                            {
                                applyPay = _dtPayDetail.Rows[i]["ApplyPay"] == null ? 0 : decimal.Parse(_dtPayDetail.Rows[i]["ApplyPay"].ToString());
                                applyPaysAndExpenseIds.Add(int.Parse(_dtPayDetail.Rows[i]["ExpenseID"].ToString()), applyPay);      //取‘本次申请额’
                                
                                //tourGroupIds.Add(int.Parse(_dtPayDetail.Rows[i]["ExpenseID"].ToString()), _dtPayDetail.Rows[i]["TourgroupID"].ToString());

                            }
                            ExpensesCtrl.UpdateExpensePayStatusData(applyPaysAndExpenseIds, PayApplyStatusEnum.已付);

                            //更新团实际成本-更新团实际成本已挪到申请付款处，此处不用了。
                            //TeamGroupCtrl.UpdateTourGroupRealCostbyGourpIDs(tourGroupIds);

                            #region 计入流水账
                            AccountManagerEntity entity = new AccountManagerEntity();
                            entity.Date = tbPayTime.DateTime.ToString("yyyy-MM-dd");
                            entity.Summary = payForm.tbRemark.EditValue.ToString();//摘要
                            entity.Income = 0;
                            entity.Expenditure = decimal.Parse(payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "TotalpaymentL").ToString()); //汇款总额
                            entity.Remark = "";
                            entity.ItemType = 0;
                            entity.ItemID = payID;
                            entity.Voucher = payForm.tbVoucher.Text;
                            entity.PaymentMethod = payForm.payGroup.Properties.Items[payForm.payGroup.SelectedIndex].Description;
                            if (payForm.payGroup.SelectedIndex == 0)
                                entity.AccountType = AccountTypeEnum.现金.ToString();
                            else
                                entity.AccountType = AccountTypeEnum.银行.ToString();
                            entity.Transactor = currentUser;

                            AccountManagerCtrl.CreateAccountManagerData(entity);
                            #endregion
                            break;
                        case 1://支票预付
                            Status = PayStatusEnum.预付;
                            PayApplyCtrl.UpdatePayApplyPayStatus(tbPayTime.DateTime, Status, "支票", payForm.tbVoucher.Text, payForm.tbRemark.Text, currentUser, payApplyId);
                            break;
                        //case 2://月结，此状态已放弃
                        //    Status = PayStatusEnum.已付;
                        //    PayApplyCtrl.UpdatePayApplyPayStatus(tbPayTime.DateTime, Status, payForm.bigClassGroup.Properties.Items[2].Description, payForm.tbVoucher.Text, payForm.tbRemark.Text, currentUser, payApplyId);

                        //    //修改费用表‘支付状态’为‘月结’,并将本次申请额送到后台，由Sql完成‘已支付总额’计算后更新‘已支付总额’
                        //    int[] Ids = new int[_dtPayDetail.Rows.Count];

                        //    for (int i = 0; i < _dtPayDetail.Rows.Count; i++)
                        //        Ids[i]=int.Parse(_dtPayDetail.Rows[i]["ExpenseID"].ToString());
                            
                        //    ExpensesCtrl.UpdateExpensePayStatusData(Ids, PayApplyStatusEnum.月结);
                        //    break;
                        default: break;
                    }

                    btnRefresh.PerformClick();
                }
            }
        }

        /// <summary>
        /// 撤销付款申请
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancelPayRequest_Click(object sender, EventArgs e)
        {
            if (payApplyGridView.FocusedRowHandle < 0) return;

            foreach (DataRow dr in _dtPayDetail.Rows)
            {
                if (dr["Status"].ToString() == ExpenseStatusEnum.终结.ToString())
                {
                    MessageBox.Show("付款单中有费用已经终结，不能撤销");
                    return;
                }
            }


            if (MessageBox.Show("请确认是否撤销此付款申请单？此操作不可恢复！", "撤销确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string payApplyId = payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "PayApplyID").ToString();

                //首先处理 费用表中‘已申请总额’项，应减掉本次申请额（必修先行处理）
                //_dtPayDetail = PayDetailCtrl.GetPayDetailDataByPayApplyId(payApplyId);
                
                Dictionary<int,decimal> data=new Dictionary<int,decimal>();
                decimal applyPay, applyPayTotal;
                int expenseId;
                Dictionary<int, string> tourGroupIds = new Dictionary<int, string>();


                //删除指定的付款申请单数据及其连带的付款详情数据
                PayApplyCtrl.DeletePayApplyAndPayDetail(payApplyId);

                foreach (DataRow dr in _dtPayDetail.Rows)
                {
                    applyPay = decimal.Parse(dr["ApplyPay"].ToString());//本次申请额
                    applyPayTotal = decimal.Parse(dr["ApplyPayTotal"].ToString());//已申请总额
                    expenseId = int.Parse(dr["ExpenseID"].ToString());//PK-ID

                    data.Add(expenseId, applyPayTotal - applyPay);
                    //更新费用状态为“计划”
                    ExpensesCtrl.UpdateExpenseStatusData(expenseId.ToString(), ExpenseStatusEnum.计划);

                    tourGroupIds.Add(int.Parse(dr["ExpenseID"].ToString()), dr["TourgroupID"].ToString());
                    
                    ExpensesCtrl.UpdateExpenseApplyPayTotal(expenseId);

                }

                //更新团实际成本
                TeamGroupCtrl.UpdateTourGroupRealCostbyGourpIDs(tourGroupIds);


                //先刷新界面
                //payApplyGridView.DeleteRow(payApplyGridView.FocusedRowHandle);
                //焦点行减一，避免取消后失去焦点行
                payApplyGridView.FocusedRowHandle = payApplyGridView.FocusedRowHandle - 1;
                btnRefresh.PerformClick();
                
                //ButtonStatus();

                //if (payApplyGridView.FocusedRowHandle < 0)
                //{
                //    payDetailGridControl.DataSource = null;
                //}
                //else
                //{
                //    payApplyId = payApplyGridView.GetRowCellValue(payApplyGridView.FocusedRowHandle, "PayApplyID").ToString();
                //    _dtPayDetail = PayDetailCtrl.GetPayDetailDataByPayApplyId(payApplyId);
                //    payDetailGridControl.DataSource = _dtPayDetail;
                //}
            }
        }
    }
}
